
const { sendRes, socketLinks, socketMap } = require('./data')
const { guid, getUrlPrefix } = require('./utils')

module.exports = function (app, io) {

    app.get('/api/socketLinks', (req, res) => {
        res.send(socketLinks)
    })

    app.use('/**', function(req, res){

        let prefix = getUrlPrefix(req.originalUrl)

        // if (prefix == 'api' || prefix == 'favicon.ico') {
        //     return
        // }

        let router = socketLinks.findRouter(prefix)

        if (!router) {
            return res.send("路由未被配置")
        }

        // 请求路劲
        let code = guid()
        var data = {
            url : req.originalUrl.replace('/' + prefix, ''),
            port : router.port,
            host : router.host,
            data : req.body,
            code,
            method : req.method,
            headers : req.headers,
            type : router.type,
            path : router.path
        }
        try{
            sendRes[code] = res

            // var toSocket = findListMapByKey(io.sockets.sockets, router.socketId, 'id');

            delete data.headers.host

            socketMap.emit(router.socketId, 'send', data)

        }catch(e){
            console.log(e);
        }
    })
}

